package com.after.saas.common.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.PostConstruct;

/**
 * @Description 雪花算法工具类
 * @Classname SnowFlakeUtil
 * @Author hjchen
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2022/9/1 9:18
 */

@Slf4j
public class SnowFlakeUtil {

    private static long workerId = 0;

    private static long datacenterId = 1;

    private static Snowflake snowflake = IdUtil.getSnowflake(workerId, datacenterId);

    @PostConstruct
    public void init() {
        try {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            log.info("当前机器的IP： {}, workerId: {}", NetUtil.getLocalhostStr(), workerId);
        } catch (Exception e) {
            log.error("获取当前机器workerId 异常", e);
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }

    /**
     * 生成long 类型的ID
     * @return
     */
    public static Long getId() {
        return snowflake.nextId();
    }

    /**
     * 生成String 类型的ID
     * @return
     */
    public static String getIdStr() {
        return snowflake.nextIdStr();
    }

}

